//
//  TCSGSOLStory.m
//  StoryGrabber
//
//  Created by Thomas on 8/19/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "TCSGSOLStory.h"
#define VERSION 0.1
@interface TCSGSOLStory (private)
- (NSString *)getChapter:(NSString *)chapterID fromStory:(NSString *)storyID type:(int)type chapterNumber:(int)number;
- (NSString *)getMultipleStory:(NSString *)storyID;
@end

@implementation TCSGSOLStory
-(int)version
{
	return VERSION;
}
-(NSString *)hostName;
{
	return @"StoriesOnline.net";
}

-(NSImage *)hostImage;
{
	return [[NSImage alloc] initWithContentsOfFile:[NSBundle pathForResource:@"SOL" ofType:@"png" inDirectory:[[NSBundle bundleForClass:[self class]] bundlePath] ]];
}
-(BOOL)respondsToAuthor;
{
	return YES;
}
-(NSString *)pluginAuthor;
{
	return @"Thomas Cool";
}

-(id)init
{
	self=[super init];
	running = YES;
	storyArray = [[NSArray alloc] init];
	return self;
}
-(void)dealloc
{
	[[NSNotificationCenter defaultCenter] removeObserver:self name:TCSGRunning object:nil];
	[storyArray release];
	[theStoryList release];
	[super dealloc];
	
}
-(void)setStoryList:(SGStoryList *)storyList;
{
	theStoryList = storyList;
}
-(void)setRunning:(NSNotification *)note
{
	running = [[note object] boolValue];
}

-(NSArray *)getStoriesArrayForAuthor:(NSString *)authorID
{
	//Define AuthorURL 
	NSString *authorURL		= [@"http://storiesonline.net/auth/" stringByAppendingPathComponent:authorID];
	
	NSString *page1				= [NSString stringWithContentsOfURL:[NSURL URLWithString:authorURL]];
	NSRange rangeStart			= [page1 rangeOfString:@"<h4 id=\"sm-a-head\">"];
	NSRange rangeEnd			= [page1 rangeOfString:@"</h4>"];
	NSRange numberRange;
	NSMutableArray *finalStoriesArray = [[NSMutableArray alloc] init];
	
	if(rangeStart.location==NSNotFound)
	{
		finalStoriesArray = [NSArray arrayWithObject:authorID];
	}
	else
	{
		numberRange.location		= rangeStart.location + rangeStart.length;
		numberRange.length			= rangeEnd.location - numberRange.location;
		NSString *numberOfStories	= [[[page1 substringWithRange:numberRange] componentsSeparatedByString:@" of "] objectAtIndex:1];
		[TCSGGeneralMethods setLabelField:[NSString stringWithFormat:@"number of stories: %@",numberOfStories]];
		int i = 0;
		int storiesNumber=[numberOfStories intValue];
		while(i*10<storiesNumber)
		{
			NSString *page = [NSString stringWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://storiesonline.net/library/author.php?name=%@&sf=story_name&so=asc&skip=%i", authorID,i*10]]];
			i++;
			NSMutableArray *seperating=[[page componentsSeparatedByString:@"<td class=\"lc2\"><a href=\"/story/"] mutableCopy];
			int z;
			for(z=0;z<[seperating count];z++)
			{
				NSRange stop		=[[seperating objectAtIndex:z] rangeOfString:@"\">"];
				if(stop.location !=NSNotFound || stop.location>15)
				{
					[seperating replaceObjectAtIndex:z withObject:[[seperating objectAtIndex:z] substringToIndex:stop.location]];
				}
				else
				{
					[seperating replaceObjectAtIndex:z withObject:@"000"];
				}
			}
			[seperating removeObjectAtIndex:0];
			[finalStoriesArray addObjectsFromArray:seperating];
		}
		
	}
	
	return finalStoriesArray;
}
-(NSString *)getHTMLWithCookies:(NSString *)url
{
	NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
	//NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
	NSURLResponse *response;
	NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
	NSString *content = [[NSString alloc]  initWithBytes:[data bytes]
												  length:[data length] encoding: NSUTF8StringEncoding];
	return [content autorelease];
}
-(NSDictionary *)getStory:(NSString *)storyID
{
	NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; 
	[nc addObserver:self 
           selector:@selector(setRunning:) 
               name:TCSGRunning
             object:nil]; 
	[TCSGGeneralMethods setLabelField:@"gettingStoryType"];
	NSString *page = [self getHTMLWithCookies:[NSString stringWithFormat:@"http://storiesonline.net/story/%@",storyID,nil]];
	
	//Title and Author
	NSRange titleStart		= [page rangeOfString:@"<title>"];
	NSRange titleEnd		= [page rangeOfString:@"</title>"];
	NSRange titleRange;
	titleRange.location		= titleStart.location+titleStart.length;
	titleRange.length		= titleEnd.location-titleRange.location;
	NSString *author		= [[[page substringWithRange:titleRange] componentsSeparatedByString:@": "]	objectAtIndex:0];
	NSString *title			= [[[page substringWithRange:titleRange] componentsSeparatedByString:@": "]	objectAtIndex:1];
	if([title rangeOfString:@" (Page 1)"].location!=NSNotFound)
	{
		title = [title substringToIndex:[title rangeOfString:@" (Page 1)"].location];
	}
	
	
	NSRange divdiv = [page rangeOfString:@"</div></div>"];
	NSString *story = [[NSString alloc] init];
	
	if(divdiv.location!=NSNotFound)
	{
		//IndexFound - multiple Chapters
		[TCSGGeneralMethods setLabelField:@"Multiple Chaptered Story"];
		story = [self getMultipleStory:storyID];
		story = [NSString stringWithFormat:@"<body>\n<h1 class=\"Chapter\">%@</h1><h3 class=\"Author\">%@</h3>\n%@\n</body>",title,author,story,nil];		
	}
	else
	{
		
		//Title and Author
		NSRange parserRange = [page rangeOfString:@"span class=\"pager\">Pages: Prev"];
		
		if(parserRange.location != NSNotFound)
		{
			
			NSString *pagetoo=page;
			BOOL end = FALSE;
			int i=0;
			[TCSGGeneralMethods setLabelField:@"Single Chapter multiple Part Story"];
			NSRange story1Start	= [pagetoo rangeOfString:@"<p>"];
			NSRange html1End	= [pagetoo rangeOfString:@"</html>"];
			NSRange search1Range;
			search1Range.location= story1Start.location;//+p1s.length;
			search1Range.length	= html1End.location-search1Range.location;
			NSRange story1End	= [pagetoo rangeOfString:@"<span class=\"conTag"];// options:NSCaseInsensitiveSearch range:search1Range];
			NSRange story1Range;
			story1Range.location= story1Start.location;
			story1Range.length	=story1End.location-story1Range.location;
			story = [page substringWithRange:story1Range];
			
			
			while(end==FALSE)
			{
				i++;
				NSString *page = [self getHTMLWithCookies:[NSString stringWithFormat:@"http://storiesonline.net/story/%@;%i",storyID,i,nil]];
				NSRange endRange = [page rangeOfString:@"| Next</span><br><br>"];
				NSRange pagerRange	= [page rangeOfString:@"<span class=\"pager\">"];
				NSRange pageEnd		= [page rangeOfString:@"</html>"];
				NSRange searchRange;
				searchRange.location= pagerRange.location+pagerRange.length;
				searchRange.length	= pageEnd.location-searchRange.location;
				NSRange storyEnd	= [page rangeOfString:@"<span class=\"pager\">" options:NSCaseInsensitiveSearch range:searchRange];
				NSRange storyStart	= [page rangeOfString:@"<p>"];
				NSRange pageRange;
				pageRange.location	= storyStart.location;
				pageRange.length	= storyEnd.location-pageRange.location;
				//page = [page substringWithRange:pageRange];
				page = [page substringWithRange:pageRange];
				story = [NSString stringWithFormat:@"%@\n\n<br>%@",story,page];
				if(endRange.location !=NSNotFound)		{end=TRUE;}
				
				
			}
			story = [NSString stringWithFormat:@"<body>\n<h1 class=\"Chapter\">%@</h1><h3 class=\"Author\">%@</h3>\n%@\n</body>",title,author,story,nil];
			storyArray = [NSArray arrayWithObject:story];
			
		}
		else
		{
			[TCSGGeneralMethods setLabelField:@"Single Chapter Story"];
			//Story
			NSRange storyStart		= [page rangeOfString:@"</h4>"];
			NSRange storyEnd		= [page rangeOfString:@"<div id=\"vote-form\">"];
			if(storyEnd.location==NSNotFound)
			{
				storyEnd = [page rangeOfString:@"<h2 class=\"end\""];
			}
			NSRange storyRange;
			storyRange.location		= storyStart.location+storyStart.length;
			storyRange.length		= storyEnd.location-storyRange.location;
			story			= [page substringWithRange:storyRange];
			//Combine
			story = [NSString stringWithFormat:@"<body>\n<h1 class=\"Chapter\">%@</h1><h3 class=\"Author\">%@</h3>\n%@\n</body>",title,author,story,nil];
			storyArray = [NSArray arrayWithObject:story];
		}
		
	}
	NSMutableDictionary *returnDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
									   story,STORYKEY,
									   title,TITLEKEY,
									   author,AUTHORKEY,
									   @"StoriesOnline",HOSTKEY,
									   storyID, IDKEY,
									   [NSNumber numberWithBool:YES],CHECKKEY,
									   storyArray,ARRAYKEY,
									   nil];
	[nc removeObserver:self name:TCSGRunning object:nil];
	[nc release];
	return returnDict;
}
- (NSDictionary *)getMoreInfoForID:(NSString *)storyID
{
	NSString *pageInfo = [NSString stringWithContentsOfURL:
						  [NSURL URLWithString:
						   [NSString stringWithFormat:@"http://storiesonline.net/library/storyInfo.php?id=%@",storyID,nil]]];
	NSRange part1 = [pageInfo rangeOfString:@"<td class=\"lc4\">"];
	pageInfo = [pageInfo substringFromIndex:(part1.location +part1.length)];
	NSRange part2 = [pageInfo rangeOfString:@"</td>"];
	pageInfo = [pageInfo substringToIndex:(part2.location)];
	NSArray *pageInfoArray =[pageInfo componentsSeparatedByString:@"<br><b>"];
	int i;
	NSMutableDictionary *extraInfo = [[NSMutableDictionary alloc] init];
	[extraInfo setObject:[[[pageInfoArray objectAtIndex:0] componentsSeparatedByString:@"</b>"] objectAtIndex:0] forKey:@"Summary"];
	for(i=1;i<[pageInfoArray count];i++)
	{
		NSString *tempType = [[[pageInfoArray objectAtIndex:i] componentsSeparatedByString:@"</b>"] objectAtIndex:0];
		NSString *tempString = [[[[pageInfoArray objectAtIndex:i] componentsSeparatedByString:@"</b>"] objectAtIndex:1] substringFromIndex:1];
		//Remove Breaklines
		
		if([tempString hasSuffix:@"\n"])			{tempString = [tempString substringToIndex:([tempString length]-1)];}
		if([tempType hasSuffix:@":"])				{tempType   = [tempType substringToIndex:([tempType length]-1)];}
		//Fix Posted Problem
		if([tempType isEqualToString:@"Posted"])	{tempString = [[tempString componentsSeparatedByString:@" <br>"] objectAtIndex:0];}
		
		[extraInfo setObject:tempString forKey:tempType];
		
	}
	return extraInfo;
}
- (NSString *)getMultipleStory:(NSString *)storyID
{
	NSMutableArray *tempStoryArray = [[NSMutableArray alloc] init];
	//NSLog(@"storyID: %@",storyID);
	
	NSArray *indexPage = [[NSString stringWithContentsOfURL:
						   [NSURL URLWithString:
							[NSString stringWithFormat:@"http://storiesonline.net/story/%@:i",storyID,nil]]]
						  componentsSeparatedByString:@"<span class=\"link\">"];
	//NSLog(@"indexPage: %@",indexPage);
	NSMutableArray *chapterIDs = [[NSMutableArray alloc] init];
	//NSLog(@"chapterIDs: %@",chapterIDs);
	int i;
	for(i=1;i<[indexPage count];i++)
	{
		NSRange d = [[indexPage objectAtIndex:i] rangeOfString:@":d"];
		[chapterIDs addObject:[[[[indexPage objectAtIndex:i] substringToIndex:d.location] componentsSeparatedByString:@":"] objectAtIndex:1]];
	}
	//NSLog(@"chapterIDs: %@",chapterIDs);
	NSString * story = @"";
	for(i=0;i<[chapterIDs count];i++)
	{
		//NSLog(@"1:%i",i);
		if(running)
		{
			[TCSGGeneralMethods setLabelField:[NSString stringWithFormat:@"getting chapter: %i",(i+1),nil]];
			NSString *chapter = [self getChapter:[chapterIDs objectAtIndex:i] fromStory:storyID type:0 chapterNumber:(i+1)];
			[tempStoryArray addObject:chapter];
			story = [NSString stringWithFormat:@"%@\n\n\n<br><br>%@",story,chapter,nil];
			
		}
		storyArray = [NSArray arrayWithArray:tempStoryArray];
		
	}
	
	[TCSGGeneralMethods setLabelField:@"multiple done"];
	return story;
}
- (NSString *)getChapter:(NSString *)chapterID fromStory:(NSString *)storyID type:(int)type chapterNumber:(int)number
{
	NSString *page = [self getHTMLWithCookies:[NSString stringWithFormat:@"http://storiesonline.net/story/%@:%@:d",storyID,chapterID,nil]];
	
	NSRange storyStart=[page rangeOfString:@"<p>"];
	NSRange storyEnd = [page rangeOfString:@"<h3 class=\"end\">"];
	if(storyEnd.location == NSNotFound)
	{
		//NSLog(@"not found");
		storyEnd = [page rangeOfString:@"<h2 class=\"end\""];
	}
	NSRange rangeFinal;
	rangeFinal.location = storyStart.location;
	rangeFinal.length = storyEnd.location-rangeFinal.location;
	NSString *tempString = [page substringWithRange:rangeFinal];
	tempString = [NSString stringWithFormat:@"<h2 class=\"chapter\">Chapter %i</h2>\n<br>%@",number,tempString,nil];
	return tempString;
}
@end
